package org.ucas.faker.web.controller;

import com.itextpdf.text.DocumentException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.ucas.faker.web.annotation.Registry;
import org.ucas.faker.web.dto.ResponseDto;
import org.ucas.faker.web.entity.Depot;
import org.ucas.faker.web.entity.TaskLog;
import org.ucas.faker.web.exceptions.InternalServerException;
import org.ucas.faker.web.service.DepotService;
import org.ucas.faker.web.service.LockService;
import org.ucas.faker.web.utils.report.ReportWord;
import org.ucas.faker.web.utils.model.Coordinator;

import sun.misc.BASE64Decoder;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class ReportController extends BaseController{

  @Autowired
  private LockService lockService;
  
  @Autowired
  private DepotService depotService;

  @Registry(code = "0001",subscriber = "zhangyipin")
  @RequestMapping(value = "/draw/pic",method = RequestMethod.POST)
  public ResponseDto drawPicByBase(@RequestParam("base64Info") String base64Info, @RequestParam("name") String name) {
    base64Info = base64Info.replaceAll(" ", "+");
    BASE64Decoder decoder = new BASE64Decoder();
    String[] arr = base64Info.split("base64,");

    //TaskLog task = buildTask(TaskLog.TaskCategory.GEN_REPORT);

    //if(!lockService.tryLock(task)) throw InternalServerException.TASK_CONFLICT;

    //String picPath = Coordinator.fileBasePath+task.getId()+Coordinator.imgPath;

    String picPath = Coordinator.fileBasePath+context().userId+"\\"+context().depotId+"\\"+Coordinator.imgPath;
    
    File realPathDirectory = new File(picPath);
    
    if(name.equals("1")) {
    	File [] files = realPathDirectory.listFiles();
    	if(files!=null) {
    		for (int i = 0; i < files.length; i++)
            {
                File file1 = files[i];
                file1.delete();
            }	
    	}
		
    }
    if (realPathDirectory == null || !realPathDirectory.exists()) {
      realPathDirectory.mkdirs();
    }
    try {
      File uploadFile = new File(realPathDirectory.getPath() + "/" + name+".png");
      byte[] buffer = decoder.decodeBuffer(arr[1]);
      OutputStream os = new FileOutputStream(uploadFile);
      os.write(buffer);
      os.close();

    } catch (IOException e) {
      //lockService.cancel(task);
      throw new RuntimeException();
    }

    //lockService.unlock(task);
    return ResponseDto.OK;
  }
  @Registry(code = "0003",subscriber = "zhangyipin")
  @RequestMapping(value = "/make/report",method = RequestMethod.GET)
  public ResponseDto makeReport1() throws  IOException, DocumentException, com.lowagie.text.DocumentException {

	  Depot depot = currentDepot();
//	  TaskLog task = taskService.load(depot.getId(),depot.getVersion(), TaskLog.TaskCategory.GEN_REPORT);
//	  if(task == null) throw InternalServerException.TASK_DEP;
    ReportWord.makeReport(context().userId,context().depotId);
//    taskService.updateStatus(task.getId(), TaskLog.TaskStatus.FINISHED,null);
    depot.setReportPath(Coordinator.fileBasePath+context().userId+"\\"+context().depotId+"\\"+Coordinator.wordPath);
    depotService.save(depot);
    return ResponseDto.OK;
  }
  
  
  @ResponseBody
  @RequestMapping(value = "/report/download/pdfres",method = RequestMethod.GET)
  public void downloadPdfFile(HttpServletRequest request, HttpServletResponse response)
      throws IOException, InvalidFormatException {
    //在指定目录中生成文件

    String fileName ="/result.pdf";
    Long taskId = currentTaskId(TaskLog.TaskCategory.GEN_REPORT);
    String filepath = Coordinator.fileBasePath+taskId+Coordinator.pdfPath+fileName ;  //TODO  注意修改路径

    int beginIndex = filepath.lastIndexOf(File.separator);
    int endIndex = filepath.lastIndexOf(".");

    response.setHeader("Content-Disposition", "attachment;filename="
        + fileName);

    BufferedInputStream bis = null;
    FileInputStream fis = null;
    BufferedOutputStream bos = null;

    try {
      fis = new FileInputStream(filepath);
      bis = new BufferedInputStream(fis);

      int length = bis.available();
      response.setContentLength(length);

      bos = new BufferedOutputStream(response.getOutputStream());
      byte[] data = new byte[1024];
      while (bis.read(data) != -1) {
        bos.write(data);
        bos.flush();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        fis.close();
        bis.close();
      } catch (IOException e) {}
    }
  }
  
  
  @ResponseBody
  @RequestMapping(value = "/report/download/wordres",method = RequestMethod.GET)
  public void downloadWordFile(HttpServletRequest request, HttpServletResponse response)
      throws IOException, InvalidFormatException {
    //在指定目录中生成文件

    String fileName ="/result.doc";
    //Long taskId = currentTaskId(TaskLog.TaskCategory.GEN_REPORT);
    String filepath = Coordinator.fileBasePath+context().userId+"\\"+context().depotId+"\\"+Coordinator.wordPath+fileName ;  //TODO  注意修改路径

    int beginIndex = filepath.lastIndexOf(File.separator);
    int endIndex = filepath.lastIndexOf(".");

    response.setHeader("Content-Disposition", "attachment;filename="
        + fileName);

    BufferedInputStream bis = null;
    FileInputStream fis = null;
    BufferedOutputStream bos = null;

    try {
      fis = new FileInputStream(filepath);
      bis = new BufferedInputStream(fis);

      int length = bis.available();
      response.setContentLength(length);

      bos = new BufferedOutputStream(response.getOutputStream());
      byte[] data = new byte[1024];
      while (bis.read(data) != -1) {
        bos.write(data);
        bos.flush();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        fis.close();
        bis.close();
      } catch (IOException e) {}
    }
  }
}
